import axios from 'axios';
import {userStore} from '../store/modules/user'
import { message } from 'ant-design-vue';
import {  goLogin } from './auth'

const service = axios.create({
    baseURL: '',
    method: 'post',
    timeout: 10000,
    data: 'json',
    responseType: 'json',
})

service.interceptors.request.use(config => {
    console.log(userStore);
    if (userStore.store.state.user.token) {
        config.headers['Authorization'] = 'Duolun ' + userStore.store.state.user.token
    }
    config.headers['systemNo'] = import.meta.env.VITE_APP_SYSTEM_NO // 系统编号
    return config
}, error => {
    console.error(error) // for debug
    return Promise.reject(error)
})

service.interceptors.response.use(
    (response) => {
        const msg = response.data.message
        const states = response.data.success
        console.log(states);
        if (!states) {
            message.error(msg || 'Error')
            return Promise.reject(new Error(msg || 'Error'))
        } else {
            return response.data
        }
    },
    (error) => {
        console.log(error.response);
        if (error.response) {
            const code = error.response.status
            if (code === 401) {
                message.error('登录状态过期了,重新登录...')
                goLogin(1)
            } else {
                message.error('服务异常')
            }
        } else {
            message.error('服务异常')
        }
        return Promise.reject(error)
    }
)

export default service